package org.jeecg.modules.oa.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;

import org.jeecg.modules.oa.entity.ButtonCondition;
import org.jeecg.modules.oa.entity.ButtonConditionNew;
import org.jeecg.modules.oa.entity.NodeButtonNew;
import org.jeecg.modules.oa.service.IButtonConditionNewService;
import org.jeecg.modules.oa.service.IButtonConditionService;
import org.jeecg.modules.oa.service.INodeButtonNewService;
import org.jeecg.modules.oa.vo.NodeButtonNewPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 节点
 * @Author: jeecg-boot
 * @Date:   2019-12-17
 * @Version: V1.0
 */
@RestController
@RequestMapping("b/nodeButtonNew")
@Slf4j
public class NodeButtonNewController {
	@Autowired
	private INodeButtonNewService nodeButtonNewService;
	@Autowired
	private IButtonConditionNewService buttonConditionNewService;
	@Autowired
	private IButtonConditionService buttonConditionService;
	
	/**
	  * 分页列表查询
	 * @param nodeButtonNew
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<NodeButtonNew>> queryPageList(NodeButtonNew nodeButtonNew,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<NodeButtonNew>> result = new Result<IPage<NodeButtonNew>>();
		QueryWrapper<NodeButtonNew> queryWrapper = QueryGenerator.initQueryWrapper(nodeButtonNew, req.getParameterMap());
		Page<NodeButtonNew> page = new Page<NodeButtonNew>(pageNo, pageSize);
		IPage<NodeButtonNew> pageList = nodeButtonNewService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param nodeButtonNewPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<NodeButtonNew> add(@RequestBody NodeButtonNewPage nodeButtonNewPage) {
		Result<NodeButtonNew> result = new Result<NodeButtonNew>();
		try {
			NodeButtonNew nodeButtonNew = new NodeButtonNew();
			BeanUtils.copyProperties(nodeButtonNewPage, nodeButtonNew);
			
			nodeButtonNewService.saveMain(nodeButtonNew, nodeButtonNewPage.getButtonConditionNewList());
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param nodeButtonNewPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	//更新和添加
	public Result<NodeButtonNew> edit(@RequestBody NodeButtonNewPage nodeButtonNewPage) {
		Result<NodeButtonNew> result = new Result<NodeButtonNew>();
        String conditionFlg = nodeButtonNewPage.getConditionFlg();
        if (conditionFlg == null){
            result.setMessage("请选择执行条件");
            result.setSuccess(false);
            return result;
        }
		List<ButtonConditionNew> buttonConditionNews = buttonConditionNewService.selectByMainId(nodeButtonNewPage.getSelectButtonId());
		if ( buttonConditionNews.size() > 0 ){
			buttonConditionNewService.removeByMainId(nodeButtonNewPage.getSelectButtonId());
		}
		ArrayList<ButtonConditionNew> buttonConditionList = new ArrayList<>();
		if (nodeButtonNewPage != null && nodeButtonNewPage.getButtonConditionNewList().size()>0){
			int i = 0 ;
			for (ButtonConditionNew bcn:nodeButtonNewPage.getButtonConditionNewList()) {
				//没有执行条件
				if (conditionFlg.equals("0")){
                 bcn.setButtonId(nodeButtonNewPage.getSelectButtonId());
				 bcn.setSortNo(i);
				 bcn.setConditionType(conditionFlg);//条件类类型
				//查询当前按钮是否配置条线
				buttonConditionList.add(bcn);
				}else {
					if (StringUtils.isEmpty(bcn.getConditionTxt())){
						result.setMessage("条件不能为空");
						result.setSuccess(false);
						return result;
					}
					if (StringUtils.isNotEmpty(bcn.getConditionTxt())){
						bcn.setButtonId(nodeButtonNewPage.getSelectButtonId());
						bcn.setSortNo(i);
						bcn.setConditionType(nodeButtonNewPage.getConditionFlg());//条件类型
						i = i + 1 ;
						buttonConditionList.add(bcn);
					}
				}
			}
		}
		buttonConditionNewService.saveBatch(buttonConditionList);
		//更新当前按钮状态
		try {
			buttonConditionService.updateCondition(nodeButtonNewPage.getSelectButtonId(),conditionFlg);
			result.setSuccess(true);
			result.setMessage("操作成功");
		}catch (Exception e){
			e.printStackTrace();
		}
		return  result;

	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			nodeButtonNewService.delMain(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<NodeButtonNew> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<NodeButtonNew> result = new Result<NodeButtonNew>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.nodeButtonNewService.delBatchMain(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<NodeButtonNew> queryById(@RequestParam(name="id",required=true) String id) {
		Result<NodeButtonNew> result = new Result<NodeButtonNew>();
		NodeButtonNew nodeButtonNew = nodeButtonNewService.getById(id);
		if(nodeButtonNew==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(nodeButtonNew);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryButtonConditionNewByMainId")
	public Result<List<ButtonConditionNew>> queryButtonConditionNewListByMainId(@RequestParam(name="id",required=true) String id) {
		Result<List<ButtonConditionNew>> result = new Result<List<ButtonConditionNew>>();
		List<ButtonConditionNew> buttonConditionNewList = buttonConditionNewService.selectByMainId(id);
		result.setResult(buttonConditionNewList);
		result.setSuccess(true);
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<NodeButtonNew> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              NodeButtonNew nodeButtonNew = JSON.parseObject(deString, NodeButtonNew.class);
              queryWrapper = QueryGenerator.initQueryWrapper(nodeButtonNew, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<NodeButtonNewPage> pageList = new ArrayList<NodeButtonNewPage>();
      List<NodeButtonNew> nodeButtonNewList = nodeButtonNewService.list(queryWrapper);
      for (NodeButtonNew nodeButtonNew : nodeButtonNewList) {
          NodeButtonNewPage vo = new NodeButtonNewPage();
          BeanUtils.copyProperties(nodeButtonNew, vo);
          List<ButtonConditionNew> buttonConditionNewList = buttonConditionNewService.selectByMainId(nodeButtonNew.getId());
          vo.setButtonConditionNewList(buttonConditionNewList);
          pageList.add(vo);
      }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "节点列表");
      mv.addObject(NormalExcelConstants.CLASS, NodeButtonNewPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("节点列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<NodeButtonNewPage> list = ExcelImportUtil.importExcel(file.getInputStream(), NodeButtonNewPage.class, params);
              for (NodeButtonNewPage page : list) {
                  NodeButtonNew po = new NodeButtonNew();
                  BeanUtils.copyProperties(page, po);
                  nodeButtonNewService.saveMain(po, page.getButtonConditionNewList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
